package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Auther: Tangguo
 * @Date: 2023-06-14  11:48
 */
@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {


    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(TaskDto task) {
        //1.添加任务及任务日志保存到数据库
        long taskId = IdWorker.getId();
        task.setTaskId(taskId);
        boolean success=addTaskToDb(task);

        if(success){
            //2.将符合条件的任务添加到redis中
            addTaskToRedis(task);

        }

        return taskId;
    }

    /**
     * 拉取任务
     *
     * @param taskType
     * @param priority
     * @return
     */
    @Override
    public TaskDto popTask(Integer taskType, Integer priority) {
        //1.将任务从redis的list中取出
        String key=ScheduleConstants.TOPIC+taskType+"_"+priority;//topic_1001_1
        String taskJson = cacheService.lRightPop(key);//右出
        //把jason字符串转换成对象
        TaskDto taskDto = JSON.parseObject(taskJson, TaskDto.class);

        if(taskDto==null){
            return null;
        }
        //2.将taskInfo删除
        taskinfoMapper.deleteById(taskDto.getTaskId());

        //3.将taskInfoLogs修改
        TaskinfoLogs logs = taskinfoLogsMapper.selectById(taskDto.getTaskId());
        logs.setStatus(ScheduleConstants.EXECUTED);
        taskinfoLogsMapper.updateById(logs);

        return taskDto;

    }


    /**
     添加符合条件的任务到缓存
     * 1. 如果当前任务的执行时间 <= 当前系统时间： 将任务添加到List中
     * 2. 预设时间（当前时间+5分钟） >= 如果当前任务的执行时间 > 当前系统时间：
     *      将任务添加到ZSet中
     * @param task:
     * @return void
     */
    private void addTaskToRedis(TaskDto task) {

        // String key = "1001_1"
        String key = task.getTaskType() +"_" +task.getPriority();
        //预设时间
        long zSetTime = System.currentTimeMillis() + (1000 * 60 * 5);

        long executeTime = task.getExecuteTime();
        //1. 如果当前任务的执行时间 <= 当前系统时间： 将任务添加到List中
        if (executeTime <= System.currentTimeMillis()){
            //"topic_1001_1"
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if(executeTime > System.currentTimeMillis() && executeTime <= zSetTime){
            //预设时间（当前时间+5分钟） >= 如果当前任务的执行时间 > 当前系统时间
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),executeTime);//第3参数，充当分数
        }
    }

    /**
     * 添加任务到数据库中
     * @param task:
     * @return boolean
     */
    private boolean addTaskToDb(TaskDto task) {

        boolean flag = false;

        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }


    /**
     redis定时刷新：
     *  每分钟刷新一次：将ZSet中符合条件的数据刷新到List中
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refreshRedis(){
        log.info("redis定时刷新：每分钟刷新一次：将ZSet中符合条件的数据刷新到List中...");
        //1.取出ZSet中符合条件的数据：getExecuteTime<=System.currentTimeMillins();
        Set<String> zSetKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");//{"future_1001_1"}

        for (String futureKey : zSetKeys) {   //futureKey: "future_1001_1"
            Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

            //1001_1
            String key = futureKey.split(ScheduleConstants.FUTURE)[1];  //["","1001_1"]
            //组装当前数据的topicKey
            String topicKey = ScheduleConstants.TOPIC+key;  //topicKey: "topic_1001_1"
            //将符合条件的任务转移到list中
            // -- 1. 根据futureKey找到对应的ZSet,将里面对应的tasks删除
            // -- 2. 根据topicKey找到对应的list,将里面对应的tasks添加
            if (tasks != null && tasks.size() > 0 ) {
                cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
            }
        }

    }

    @PostConstruct
    public void refreshDBToRedis(){
        //1.清空redis中的任务
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
        //2.查询数据库中未来5分钟的任务
        //预设时间
        long zSetTime = System.currentTimeMillis() + (1000 * 60 * 5);
        List<Taskinfo> allTasks = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime,zSetTime));
        if(allTasks != null && allTasks.size() > 0){
            for (Taskinfo taskinfo : allTasks) {
                TaskDto task = new TaskDto();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                //3.将目标任务同步到redis
                addTaskToRedis(task);
            }
        }

    }
}
